package coupon

import (
	// "bp/cache"
	sqlc "bp/db/sqlc"
	"bp/internal/util"
	"context"
	"database/sql"
)

// EnsureCouponDistributionStatParam 确保CouponDistributionStat参数
type EnsureCouponDistributionStatParam struct {
	CouponDistributionPtr *sqlc.CouponDistribution
	DistributionID        int64
}

// EnsureCouponDistributionStat 确保CouponDistributionStat对一次券投放始终有一条记录并返回
func (s *CouponEntityServiceImp) EnsureCouponDistributionStat(ctx context.Context, q *sqlc.Queries, withLock bool, ptr *EnsureCouponDistributionStatParam) (couponDistributionStatPtr *sqlc.CouponDistributionStat, err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	var couponDistributionPtr *sqlc.CouponDistribution
	if ptr.CouponDistributionPtr != nil {
		couponDistributionPtr = ptr.CouponDistributionPtr
	} else {
		couponDistributionPtr, err = s.GetCouponDistributionPtr(ctx, q, ptr.DistributionID)
		if err != nil {
			return
		}
		slog.Infof("0 GetCouponDistributionPtr ok")
	}
	distributionID := couponDistributionPtr.ID
	couponID := couponDistributionPtr.CouponID

	var sqlErr error
	var couponDistributionStat sqlc.CouponDistributionStat
	if withLock {
		couponDistributionStat, sqlErr = q.GetCouponDistributionStatByDistributionIDToLock(ctx, distributionID)
	} else {
		couponDistributionStat, sqlErr = q.GetCouponDistributionStatByDistributionID(ctx, distributionID)
	}

	if sqlErr != nil {
		if sql.ErrNoRows != sqlErr {
			err = sqlErr
			return
		}
		couponPtr, getErr := s.GetCouponPtr(ctx, q, couponID)
		if getErr != nil {
			err = getErr
			return
		}
		couponDistributionStat, err = q.UpsertCouponDistributionStat(ctx, sqlc.UpsertCouponDistributionStatParams{
			BrandID:        couponPtr.BrandID,
			CouponID:       couponID,
			DistributionID: distributionID,
		})
		if err != nil {
			return
		}
	}
	couponDistributionStatPtr = &couponDistributionStat
	slog.Infof("确保CouponDistributionStat对一次券投放始终有一条记录并返回 ok")
	return
}


// RefreshCouponDistributionStatSinceMemberGotCoupon C端用户领取优惠券刷新券投放统计
func (s *CouponEntityServiceImp) RefreshCouponDistributionStatSinceMemberGotCoupon(ctx context.Context, q *sqlc.Queries, distributionID int64) (err error) {
	// slog := util.NewContextLogger(ctx, s.slog)

	err = q.UpdateCouponDistributionStatGotCnt(ctx, distributionID)
	if err != nil {
		return
	}

	// slog.Infof("C端用户领取优惠券刷新券投放统计 ok")
	return
}